package com.ruoyi.dora.portal.controller;

import java.util.HashMap;
import java.util.Map;

import com.ruoyi.common.core.domain.AjaxResult;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import static com.ruoyi.common.core.domain.AjaxResult.error;
import static com.ruoyi.common.core.domain.AjaxResult.success;

/**
 * @author lvzihai
 * @date 2021/7/22
 **/
@Slf4j
@Controller
public class LoginController {

  @GetMapping("/login")
  public String loginPage (Model model) {
    if(SecurityUtils.getSubject().isAuthenticated()){
      return "redirect:/index";
    }
    Map<String, Object> configMap = new HashMap<>();
    configMap.put("sys.account.registerUser", true);
    model.addAttribute("config", configMap);
    model.addAttribute("captchaEnabled", false);

    return "login";
  }

  @GetMapping("/logout")
  public String logout () {
    SecurityUtils.getSubject().logout();

    return "redirect:/login";
  }

  @PostMapping("/login")
  @ResponseBody
  public AjaxResult ajaxLogin (String username, String password, Boolean rememberMe) {
    UsernamePasswordToken token = new UsernamePasswordToken(username, password, rememberMe);
    Subject subject = SecurityUtils.getSubject();
    try {
      subject.login(token);
      return success();
    } catch (AuthenticationException e) {
      log.error("login error.",e);
      String msg = "用户或密码错误";
      if (StringUtils.isNotEmpty(e.getMessage())) {
        msg = e.getMessage();
      }
      return error(msg);
    }
  }


  @GetMapping("/unauth")
  public String unauth () {
    return "error/unauth";
  }

}
